#include "mock_detect_def.h"
#include <opencv2/videoio.hpp>
#include <iostream>
#include <fstream>
#include "serialize.hpp"
#include "mock_detect.h"

std::string serializeTrajectoryInfo(const TrajectoryInfo_t &info)
{
    std::ostringstream ss;
    serialize(ss, info.video_name);
    serialize(ss, info.video_width);
    serialize(ss, info.video_height);
    serialize(ss, info.video_framerate);
    for (auto& track : info.tracks)
    {
        serialize(ss, track);
    }

    return ss.str();
}


int main( int argc, const char** argv )
{
    if (0 != initDetect("haarcascade_frontalface_alt.xml"))
    {
        std::cout << "--(!)Error loading face cascade\n";
        return -1;
    }

#ifdef USE_GPU
    char env[] = "OPENCV_FFMPEG_CAPTURE_OPTIONS=video_codec;h264_cuvid";

    int rc = putenv(env);
    if (rc != 0){
        std::cout << "Could not set environment variables\n" << std::endl;
    }
#endif
    std::string video_name = "face_1280_720.h264";
    cv::VideoCapture capture;
    // Read the video stream
    capture.open(video_name);
    if ( ! capture.isOpened() )
    {
        std::cout << "--(!)Error opening video capture\n";
        return -1;
    }

    TrajectoryInfo_t info;
    info.video_name = video_name;
    info.video_width = 1280;
    info.video_height = 720;
    info.video_framerate = 25;

    cv::Mat frame;
    uint32_t index = 0;

    while (capture.read(frame))
    {
        if(frame.empty())
        {
            std::cout << "--(!) No captured frame -- Break!\n";
            break;
        }

        Track_t track;
        int count = detect(frame, track.rect);
        if (count > 0)
        {
            track.f = index;
            info.tracks.push_back(track);
        }
        std::cout << "index: " << index << " detect " << count << " faces" << std::endl;
        index++;
    }

    std::string str = serializeTrajectoryInfo(info);

    std::ofstream f("detect_result.txt", std::ofstream::binary);
    f << str;
    f.close();

    return 0;
}
